package br.fot.granola.genner.states.blinky;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import br.fot.granola.oboe.graphics.EmptyBackend;
import br.fot.granola.oboe.graphics.Node;
import br.fot.granola.oboe.util.Color;

public class SquareBackend extends EmptyBackend
{
	/** The buffer holding the vertices */
	private FloatBuffer vertexBuffer;
	
	public Color color = new Color(1, 1, 1, 1);
	
	/** The initial vertex definition */
	private float vertices[] = { 
								-1.0f, -1.0f, 0.0f, //Bottom Left
								1.0f, -1.0f, 0.0f, 	//Bottom Right
								-1.0f, 1.0f, 0.0f, 	//Top Left
								1.0f, 1.0f, 0.0f 	//Top Right
								};

	/**
	 * The Square constructor.
	 * 
	 * Initiate the buffers.
	 */
	public SquareBackend() {
		ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4);
		byteBuf.order(ByteOrder.nativeOrder());
		vertexBuffer = byteBuf.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);
	}
	
	@Override
	public void draw( Node front, GL10 gl )
	{
		gl.glTranslatef( front.position.x, front.position.y, front.position.z );

		gl.glRotatef( front.rotation.x, 1, 0, 0);
		gl.glRotatef( front.rotation.y, 0, 1, 0);
		gl.glRotatef( front.rotation.z, 0, 0, 1);
		
		gl.glScalef( front.scale.x,  front.scale.y,  front.scale.z );
		
		//Set the face rotation
		gl.glFrontFace(GL10.GL_CW);
		
		gl.glColor4f( this.color.r, this.color.g, this.color.b, this.color.a );
		
		//Point to our vertex buffer
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
		
		//Enable vertex buffer
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		
		//Draw the vertices as triangle strip
		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
		
		//Disable the client state before leaving
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
	}
}